#import "CommonCommentWebServices.h"
#import "CommonUtil.h"


@implementation CommonCommentWebServices

@synthesize webData;
@synthesize xmlParser;
@synthesize data;
@synthesize dataTable, dataType, element, bookItem;
@synthesize isRowBegin;
@synthesize isValueBegin;
@synthesize owner;

- (void)setDelegate:(NSObject<CommonCommentWebServicesProtocol> *) object {
	owner = object;
}

- (NSDictionary *)getWebServicesData:(NSString *)column page:(NSString *)page {
	[self webServicesRequest:column page:page];
}

- (void)webServicesRequest:(NSString *)column page:(NSString *)page {
	NSString *soapMessage = [NSString stringWithFormat:
                             @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                             "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                             "<soap:Header>\n"
                             "<Authentication>\n"
                             "<username>%@</username>\n"
                             "<password>%@</password>\n"
                             "</Authentication>\n"
                             "</soap:Header>\n"
                             "<soap:Body>\n"
                             "<getBookComments xmlns=\"http://www.oz77.com/\">\n"
                             "<in0></in0>\n"
                             "<in1>%@</in1>\n"
                             "<in2>%@</in2>\n"
                             "</getBookComments>\n"
                             "</soap:Body>\n"
                             "</soap:Envelope>\n", kWSUsername, kWSPassword, column, page 
                             ];
	//NSLog(soapMessage);
	
	//NSURL *url = [NSURL URLWithString:@"http://192.168.1.101:8080/changjiangpress/services/OzService"];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@services/OzService", kServerURL]];
	NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:url];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	[connectionRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[connectionRequest addValue: [NSString stringWithFormat:@"%@services/OzService/getBookComments", kServerURL] forHTTPHeaderField:@"SOAPAction"];
	[connectionRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[connectionRequest setHTTPMethod:@"POST"];
	[connectionRequest setTimeoutInterval:10.0];
	[connectionRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
	[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	
	/*请求：同步获取数据
	NSData *data = [NSURLConnection sendSynchronousRequest:connectionRequest
										 returningResponse:nil error:nil];
	
	NSString *str = [[NSString alloc]initWithData: data encoding: NSUTF8StringEncoding];
	NSLog(@">>%@", str);
	 */
	
	//请求：异步获取数据
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:connectionRequest delegate:self];
	
	//如果连接已经建好，则初始化data
	if( theConnection ) {
		webData = [[NSMutableData data] retain];
	} else {
		NSLog(@"connection is disabled.");
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[webData setLength: 0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[webData appendData:data];
}

//如果电脑没有连接网络，则出现此信息（不是网络服务器不通）
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[connection release];
	[webData release];
	[owner onCommonCommentWebServicesFaild:@"didFailWithError"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes] 
												length:[webData length] 
											  encoding:NSUTF8StringEncoding];
	//NSLog(@"source DATA:%@", theXML);
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
	
	@try {
		theXML = [CommonUtil getSubstring:theXML prefix:@"<books>" suffix:@"</books>"];
		//NSLog(@"real DATA:%@\n", theXML);
		//如果不是规则化数据，报错
		if( [theXML isEqualToString:@""] ) {
			NSLog(@"数据格式不错");
			[owner onCommonCommentWebServicesFaild:@"dataFormatError"];
			return;	
		}
	}
	@catch (NSException *e) {
		NSLog(@"NSException");
		[owner onCommonCommentWebServicesFaild:@"NSException"];
		return;
	}
	//NSLog(@"real DATA:%@", theXML);
	webData = nil;
	webData = [[NSMutableData alloc] init];
	[webData appendData:[theXML dataUsingEncoding:NSUTF8StringEncoding]];
	
	if( xmlParser ) {
		[xmlParser release];
	}
	
	dataTable = [[NSMutableArray alloc] init];
	dataType = 0;
	itemValueTmp = [[NSString alloc] init];
	element = [[NSMutableArray alloc] init];
	bookItem = [[BookItem alloc] init];
	
	xmlParser = [[NSXMLParser alloc] initWithData: webData];
	[xmlParser setDelegate: self];
	[xmlParser setShouldResolveExternalEntities: YES];
	[xmlParser parse];
	
	[connection release];
	[webData release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName 
	attributes: (NSDictionary *)attributeDict {
	
	//如果是行开始
	if([[elementName uppercaseString] isEqualToString:@"BOOK"]) {
		isRowBegin = YES;
	}
	/*
     <books><book><id>1323445961062</id><code>com.cjcb.books.dayno</code><name>日常生活禁忌</name><iconsmall></iconsmall><phone>1323445961062_3.zip</phone><phonetype>txt</phonetype><pad>1323445961062_4.zip</pad><padtype>pdf</padtype><price>1</price><price2></price2><author>刘道清, 张新涛</author><translator></translator><category>1006</category><category1>人文社科</category1><hot>0</hot><star>3</star><download>0</download><favorite>0</favorite><approvaltime>1323470481918</approvaltime></book><book><id>1323445987707</id><code>com.cjcb.books.21baby</code><name>21世纪最佳育儿法</name><iconsmall></iconsmall><phone>1323445987707_3.zip</phone><phonetype>txt</phonetype><pad>1323445987707_4.zip</pad><padtype>pdf</padtype><price>2</price><price2></price2><author>[日]七田 真</author><translator>21世纪0岁教育方案翻译组</translator><category>1006</category><category1>人文社科</category1><hot>0</hot><star>3</star><download>0</download><favorite>0</favorite><approvaltime>1323470474508</approvaltime></book></books>
     */
	if(isRowBegin) {
		//选定列
		if([[elementName uppercaseString] isEqualToString:@"ID"] ||
           [[elementName uppercaseString] isEqualToString:@"CODE"] ||
           [[elementName uppercaseString] isEqualToString:@"NAME"]||
           [[elementName uppercaseString] isEqualToString:@"ICONSMALL"]||
           
           [[elementName uppercaseString] isEqualToString:@"PHONE"]||
           [[elementName uppercaseString] isEqualToString:@"PHONETYPE"]||
           [[elementName uppercaseString] isEqualToString:@"PAD"]||
           [[elementName uppercaseString] isEqualToString:@"PADTYPE"]||
           [[elementName uppercaseString] isEqualToString:@"PRICE"]||
           [[elementName uppercaseString] isEqualToString:@"PRICE2"]||
           [[elementName uppercaseString] isEqualToString:@"AUTHOR"]||
           
           [[elementName uppercaseString] isEqualToString:@"TRANSLATOR"]||
           [[elementName uppercaseString] isEqualToString:@"CATEGORY"]||
           [[elementName uppercaseString] isEqualToString:@"CATEGORY1"]||
           [[elementName uppercaseString] isEqualToString:@"HOT"]||
           [[elementName uppercaseString] isEqualToString:@"STAR"]||
           
           [[elementName uppercaseString] isEqualToString:@"DOWNLOAD"]||
           [[elementName uppercaseString] isEqualToString:@"FAVORITE"]||
           [[elementName uppercaseString] isEqualToString:@"APPROVALTIME"]||
           [[elementName uppercaseString] isEqualToString:@"COMMENT"]
           ) {
			isValueBegin = YES;
		}
	}
} 

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
	if(isValueBegin) {
		itemValueTmp = [itemValueTmp stringByAppendingString:string];
	}
} 

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { 
	if([[elementName uppercaseString] isEqualToString:@"BOOK"]) {
		isRowBegin = NO;
        //NSLog(@"%@=%@=%@", bookItem.bookCode, bookItem.bookName, bookItem.bookPrice2);
		[dataTable addObject:bookItem];
		bookItem = [[BookItem alloc] init];
		
	}else if ([[elementName uppercaseString] isEqualToString:@"ID"]) {
		bookItem.bookId = itemValueTmp; isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"CODE"]) {
		bookItem.bookCode = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"NAME"]) {
		bookItem.bookName = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"ICONSMALL"]) {
		bookItem.bookIconSmall = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PHONE"]) {
		bookItem.book4PhoneResource = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PHONETYPE"]) {
		bookItem.book4PhoneResourceType = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PAD"]) {
		bookItem.book4PadResource = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PADTYPE"]) {
		bookItem.book4PadResourceType = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PRICE"]) {
		bookItem.bookPrice = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"PRICE2"]) {
		bookItem.bookPrice2 = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"AUTHOR"]) {
		bookItem.bookAuthor = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"TRANSLATOR"]) {
		bookItem.bookTranslator = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"CATEGORY"]) {
		bookItem.bookCategory = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"CATEGORY1"]) {
		bookItem.bookCategory1 = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"HOT"]) {
		bookItem.bookHot = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"STAR"]) {
		bookItem.bookStar= itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"DOWNLOAD"]) {
		bookItem.bookDownCount = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"FAVORITE"]) {
		bookItem.bookFocusCount = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"APPROVALTIME"]) {
		bookItem.bookApprovalTime = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if ([[elementName uppercaseString] isEqualToString:@"COMMENT"]) {
		bookItem.bookCommentCount = itemValueTmp;isValueBegin = NO; itemValueTmp = @"";
	}else if([[elementName uppercaseString] isEqualToString:@"BOOKS"]) {
		data = [[NSDictionary alloc] initWithObjectsAndKeys:
				[[NSArray alloc] initWithArray:dataTable], @"dataTable",
				nil];
		
		[dataTable release];
		[itemValueTmp release];
		
		[owner onCommonCommentWebServicesOver:data];
		
		[data release];
	}
} 

- (void)parserDidStartDocument:(NSXMLParser *)parser { 
	//NSLog(@"start parse document"); 
} 

- (void)parserDidEndDocument:(NSXMLParser *)parser { 
	//NSLog(@"end parse document"); 
}

@end
